<?php

/*
	info: 模板处理函数库
*/

if (!defined('WEBINROOT'))
{
	header("HTTP/1.0 404 Not Found");
	exit();
}

if (defined('TEMPLATE_FUNC'))
{
	return;
}
define('TEMPLATE_FUNC', TRUE);

//模板显示
function template_Display($file, $tpltype = 0)
{
	global $db, $dbc, $user, $webcache, $webglobal, $webserver, $webcookie, $webrequest, $webconfig, $weblang;
	if (function_exists('ob_gzhandler'))
	{
		ob_start('ob_gzhandler');
	}
	else
	{
		ob_start();
	}
	if (defined('TEMPLATE_TYPE'))
	{
		$tpltype = TEMPLATE_TYPE;
	}
	if ($tpltype==9)
	{
		/*
		if (defined('ADMIN_WEBINROOT') && $webglobal['adminremurl'])
		{
			global_SetCookie('adminlasturl', $webserver['pageurl']);
		}
		*/
		include template_AdminHtml($file);
	}
	elseif ($tpltype==1)
	{
		include template_MyHtml($file);
	}
	else
	{
		include template_Html($file);
	}
	ob_end_flush();
}

//模板获取
function template_Fetch($file)
{
	global $db, $dbc, $user, $webcache, $webglobal, $webserver, $webcookie, $webrequest, $webconfig, $weblang;
	ob_start();
	include template_Html($file);
	$tempContent = ob_get_contents();
	ob_end_clean();
	return $tempContent;
}

//后台css模板解析
function template_AdminCss($file)
{
	$csstemp = ADMIN_WEBFILEPATH.'/templates/'.$file.'.css';
	$cssfile = ADMIN_WEBFILEPATH.'/cache/'.$file.'.css';
	$linkcss = '<link rel="stylesheet" type="text/css" href="'.ADMIN_WEBURLPATH.'/cache/'.$file.'.css" />'."\n";
	if (!file_exists($cssfile) || @filemtime($csstemp) > @filemtime($cssfile))
	{
		if (!@$fp = fopen($csstemp, 'rb'))
		{
			exit("Current template file '$file.css' not found or have no access!");
		}
		$template = fread($fp, filesize($csstemp));
		fclose($fp);

		$template = str_replace("{WEBURLPATH}", WEBURLPATH, $template);
		$template = str_replace("{ADMIN_WEBURLPATH}", ADMIN_WEBURLPATH, $template);
		$template = str_replace("{WEBADMIN}", WEBADMIN, $template);

		$template = preg_replace("/\s*\{\s*/", "{", $template);
		$template = preg_replace("/\s*:\s*/", ":", $template);
		$template = preg_replace("/\s*;\s*/", ";", $template);
		$template = preg_replace("/\s*\}\s+/", "}\n", $template);

		if (!@$fp = fopen($cssfile, 'wb'))
		{
			exit("Current template file '$file.css' not found or have no access!");
		}
		flock($fp, 2);
		fwrite($fp, trim($template));
		fclose($fp);
		@chmod("$cssfile", 0777);
	}
	return $linkcss;
}

//后台网页模板解析
function template_AdminHtml($file)
{
	$tplfile = ADMIN_WEBFILEPATH.'/templates/'.$file.'.htm';
	$objfile = ADMIN_WEBFILEPATH.'/cache/'.$file.'.tpl.php';
	if (!file_exists($tplfile))
	{
		exit("Current template file '$file.htm' not found or have no access!");
	}
	if (!file_exists($objfile) || @filemtime($tplfile) > @filemtime($objfile))
	{
		template_Parse($tplfile, $objfile, 9);
	}
	return $objfile;
}

//个人css模板解析
function template_MyCss($file)
{
	!defined('WEBMYTEMPNAME') && define('WEBMYTEMPNAME', 'default');
	$tempnewfile = WEBMYTEMPNAME.'/'.$file;
	$csstemp = WEBFILEPATH.'/templates/my/'.$tempnewfile.'.css';
	$cssfile = WEBFILEPATH.'/cache/templates/my/'.str_replace('/', '.', $tempnewfile).'.css';
	$linkcss = '<link rel="stylesheet" type="text/css" href="'.WEBURLPATH.'/cache/templates/my/'.str_replace('/', '.', $tempnewfile).'.css" />'."\n";

	if (!file_exists($csstemp))
	{
		$csstemp = WEBFILEPATH.'/templates/my/default/'.$file.'.css';
	}
	if (!file_exists($cssfile) || @filemtime($csstemp) > @filemtime($cssfile))
	{
		if (!@$fp = fopen($csstemp, 'rb'))
		{
			exit("Current template file '$file.css' not found or have no access!");
		}
		$template = fread($fp, filesize($csstemp));
		fclose($fp);

		$template = str_replace("{WEBURLPATH}", WEBURLPATH, $template);

		$template = preg_replace("/\s*\{\s*/", "{", $template);
		$template = preg_replace("/\s*:\s*/", ":", $template);
		$template = preg_replace("/\s*;\s*/", ";", $template);
		$template = preg_replace("/\s*\}\s+/", "}\n", $template);

		if (!@$fp = fopen($cssfile, 'wb'))
		{
			exit("Current template file '$file.css' not found or have no access!");
		}
		flock($fp, 2);
		fwrite($fp, trim($template));
		fclose($fp);
		@chmod("$cssfile", 0777);
	}
	return $linkcss;
}

//个人用户模版解析
function template_MyHtml($file)
{
	!defined('WEBMYTEMPNAME') && define('WEBMYTEMPNAME', 'default');
	$tempnewfile = WEBMYTEMPNAME.'/'.$file;
	$tplfile = WEBFILEPATH.'/templates/my/'.$tempnewfile.'.htm';
	$objfile = WEBFILEPATH.'/cache/templates/my/'.str_replace('/', '.', $tempnewfile).'.tpl.php';
	if (!file_exists($tplfile))
	{
		$tplfile = WEBFILEPATH.'/templates/my/default/'.$file.'.htm';
	}
	if (!file_exists($objfile) || @filemtime($tplfile) > @filemtime($objfile))
	{
		template_Parse($tplfile, $objfile, 1);
	}
	return $objfile;
}

//CSS模板解析
function template_Css($file)
{
	$tempnewfile = WEBTEMPNAME.'/'.$file;
	$csstemp = WEBFILEPATH.'/templates/'.$tempnewfile.'.css';
	$cssfile = WEBFILEPATH.'/cache/templates/'.str_replace('/', '.', $tempnewfile).'.css';
	$linkcss = '<link rel="stylesheet" type="text/css" href="'.WEBURLPATH.'/cache/templates/'.str_replace('/', '.', $tempnewfile).'.css" />'."\n";

	if (!file_exists($csstemp))
	{
		$csstemp = WEBFILEPATH.'/templates/default/'.$file.'.css';
	}
	if (!file_exists($cssfile) || @filemtime($csstemp) > @filemtime($cssfile))
	{
		if (!@$fp = fopen($csstemp, 'rb'))
		{
			exit("Current template file '$file.css' not found or have no access!");
		}
		$template = fread($fp, filesize($csstemp));
		fclose($fp);

		$template = str_replace("{WEBURLPATH}", WEBURLPATH, $template);

		$template = preg_replace("/\s*\{\s*/", "{", $template);
		$template = preg_replace("/\s*:\s*/", ":", $template);
		$template = preg_replace("/\s*;\s*/", ";", $template);
		$template = preg_replace("/\s*\}\s+/", "}\n", $template);

		if (!@$fp = fopen($cssfile, 'wb'))
		{
			exit("Current template file '$file.css' not found or have no access!");
		}
		flock($fp, 2);
		fwrite($fp, trim($template));
		fclose($fp);
		@chmod("$cssfile", 0777);
	}
	return $linkcss;
}

//网页模板解析
function template_Html($file)
{
	$tempnewfile = WEBTEMPNAME.'/'.$file;
	$tplfile = WEBFILEPATH.'/templates/'.$tempnewfile.'.htm';
	$objfile = WEBFILEPATH.'/cache/templates/'.str_replace('/', '.', $tempnewfile).'.tpl.php';
	if (!file_exists($tplfile))
	{
		$tplfile = WEBFILEPATH.'/templates/default/'.$file.'.htm';
	}
	if (!file_exists($objfile) || @filemtime($tplfile) > @filemtime($objfile))
	{
		template_Parse($tplfile, $objfile);
	}
	return $objfile;
}

function template_Parse($tplfile, $objfile, $tpltype = 0)
{
	$nest = 5;

	if (!@$fp = fopen($tplfile, 'rb'))
	{
		exit("Current template file '".basename($tplfile)."' not found or have no access!");
	}
	$template = @fread($fp, filesize($tplfile));
	fclose($fp);

	$var_regexp = "((\\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(\[[a-zA-Z0-9_\-\.\"\'\[\]\$\x7f-\xff]+\])*)";
	$const_regexp = "([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)";

	$template = preg_replace("/([\n\r]+)\t+/s", "\\1", $template);
	$template = preg_replace("/\<\!\-\-\{(.+?)\}\-\-\>/s", "{\\1}", $template);
	$template = str_replace("{LF}", "<?=\"\\n\"?>", $template);

	$template = preg_replace("/\{(\\\$[a-zA-Z0-9_\[\]\'\"\$\.\x7f-\xff]+)\}/s", "<?=\\1?>", $template);
	$template = preg_replace("/$var_regexp/es", "template_AddQuote('<?=\\1?>')", $template);
	$template = preg_replace("/\<\?\=\<\?\=$var_regexp\?\>\?\>/es", "template_AddQuote('<?=\\1?>')", $template);

	if ($tpltype==9)
	{
		$template = "<? !defined('ADMIN_WEBINROOT') and exit(); ?>$template";
		$template = preg_replace("/[\n\r\t]*\{template\s+([a-z0-9_]+)\}[\n\r\t]*/is", "\n<? include template_AdminHtml('\\1'); ?>\n", $template);
		$template = preg_replace("/[\n\r\t]*\{templatecss\s+([a-z0-9_]+)\}[\n\r\t]*/is", "\n<? echo template_AdminCss('\\1'); ?>\n", $template);
		$template = preg_replace("/[\n\r\t]*\{template\s+(.+?)\}[\n\r\t]*/is", "\n<? include template_AdminHtml(\\1); ?>\n", $template);
	}
	elseif ($tpltype==1)
	{
		$template = "<? !defined('WEBINROOT') and exit(); ?>$template";
		$template = preg_replace("/[\n\r\t]*\{template\s+([a-z0-9_\/]+)\}[\n\r\t]*/is", "\n<? include template_MyHtml('\\1'); ?>\n", $template);
		$template = preg_replace("/[\n\r\t]*\{templatecss\s+([a-z0-9_\/]+)\}[\n\r\t]*/is", "\n<? echo template_MyCss('\\1'); ?>\n", $template);
		$template = preg_replace("/[\n\r\t]*\{template\s+(.+?)\}[\n\r\t]*/is", "\n<? include template_MyHtml(\\1); ?>\n", $template);
	}
	else
	{
		$template = "<? !defined('WEBINROOT') and exit(); ?>$template";
		$template = preg_replace("/[\n\r\t]*\{template\s+([a-z0-9_\/]+)\}[\n\r\t]*/is", "\n<? include template_Html('\\1'); ?>\n", $template);
		$template = preg_replace("/[\n\r\t]*\{templatecss\s+([a-z0-9_\/]+)\}[\n\r\t]*/is", "\n<? echo template_Css('\\1'); ?>\n", $template);
		$template = preg_replace("/[\n\r\t]*\{template\s+(.+?)\}[\n\r\t]*/is", "\n<? include template_Html(\\1); ?>\n", $template);
	}

	$template = preg_replace("/[\n\r\t]*\{lang\:(.+?)\}[\n\r\t]*/ies", "template_TransLang('\\1')", $template);
	$template = preg_replace("/[\n\r\t]*\{eval\s+(.+?)\}[\n\r\t]*/ies", "template_StripvTags('<? \\1 ?>','')", $template);
	$template = preg_replace("/[\n\r\t]*\{echo\s+(.+?)\}[\n\r\t]*/ies", "template_StripvTags('<? echo \\1; ?>','')", $template);
	$template = preg_replace("/([\n\r\t]*)\{elseif\s+(.+?)\}([\n\r\t]*)/ies", "template_StripvTags('\\1<? } elseif(\\2) { ?>\\3','')", $template);
	$template = preg_replace("/([\n\r\t]*)\{else\}([\n\r\t]*)/is", "\\1<? } else { ?>\\2", $template);

	for ($i=0; $i<$nest; $i++)
	{
		$template = preg_replace("/[\n\r\t]*\{loop\s+(\S+)\s+(\S+)\}[\n\r]*(.+?)[\n\r]*\{\/loop\}[\n\r\t]*/ies", "template_StripvTags('<? if(is_array(\\1)) { foreach(\\1 as \\2) { ?>','\\3<? } } ?>')", $template);
		$template = preg_replace("/[\n\r\t]*\{loop\s+(\S+)\s+(\S+)\s+(\S+)\}[\n\r\t]*(.+?)[\n\r\t]*\{\/loop\}[\n\r\t]*/ies", "template_StripvTags('<? if(is_array(\\1)) { foreach(\\1 as \\2 => \\3) { ?>','\\4<? } } ?>')", $template);
		$template = preg_replace("/([\n\r\t]*)\{if\s+(.+?)\}([\n\r]*)(.+?)([\n\r]*)\{\/if\}([\n\r\t]*)/ies", "template_StripvTags('\\1<? if(\\2) { ?>\\3','\\4\\5<? } ?>\\6')", $template);
	}

	$template = preg_replace("/\{$const_regexp\}/s", "<?=\\1?>", $template);
	$template = preg_replace("/[\n\r\t]*\{block\s+([a-zA-Z0-9_]+)\}(.+?)\{\/block\}/ies", "template_StripBlock('\\1', '\\2')", $template);
	$template = preg_replace("/\s+\?\>[\n\r]*\<\?\s+/s", "\n", $template);
	$template = preg_replace("/\"(http)?[\w\.\/:]+\?[^\"]+?&[^\"]+?\"/e", "template_TransAmp('\\0')", $template);

	global_CreateFolder(dirname($objfile));
	if (!@$fp = fopen($objfile, 'wb'))
	{
		exit("Directory '".preg_replace("/^".preg_quote(WEBFILEPATH, '/')."/", "", dirname($objfile))."' not found or have no access!");
	}
	flock($fp, 2);
	fwrite($fp, trim($template));
	fclose($fp);
	@chmod("$objfile", 0777);
}

function template_AddQuote($var)
{
	return str_replace("\\\"", "\"", preg_replace("/\[([a-zA-Z0-9_\-\.\x7f-\xff]+)\]/s", "['\\1']", $var));
}

function template_StripBlock($var, $s)
{
	$s = str_replace('\"', '"', $s);
	$s = preg_replace("/<\?=\\\$(.+?)\?>/", "{\$\\1}", $s);
	preg_match_all("/<\?=(.+?)\?>/e", $s, $constary);
	$constadd = '';
	$constary[1] = array_unique($constary[1]);
	foreach ($constary[1] as $const)
	{
		$constadd .= '$__'.$const.' = '.$const.";\n";
	}
	$s = preg_replace("/<\?=(.+?)\?>/", "{\$__\\1}", $s);
	$s = str_replace('?>', "\n\$$var .= <<<EOF\n", $s);
	$s = str_replace('<?', "\nEOF;\n", $s);
	return "\n<?\n$constadd\$$var = <<<EOF\n".$s."\nEOF;\n?>\n";
}

function template_StripvTags($expr, $statement)
{
	$expr = str_replace("\\\"", "\"", preg_replace("/\<\?\=(\\\$.+?)\?\>/s", "\\1", $expr));
	$statement = str_replace("\\\"", "\"", $statement);
	return $expr.$statement;
}

function template_TransAmp($str)
{
	$str = str_replace('&', '&amp;', $str);
	$str = str_replace('&amp;amp;', '&amp;', $str);
	$str = str_replace('\"', '"', $str);
	return $str;
}

function template_TransLang($expr)
{
	$expr = str_replace("\\\"", "\"", preg_replace("/\<\?\=(\\\$.+?)\?\>/s", "\\1", $expr));
	$tempArray = explode('@@', $expr);
	$tempArray[0] = "'{$tempArray[0]}'";
	return "<? echo global_FormatLang(".str_replace("'.'", "", implode(".'@@'.", $tempArray))."); ?>";
}
